<?php

class ServiceController extends MyController
{

//    protected $type = Users::TYPE_CUSTOMER;
    // Filter
    public $filterBusiness = 0;
    public $filterStaff    = 0;
    public $currentLimit   = 100;

    public function actionIndex()
    {
        $model             = new Service('search');
        if (isset($_GET['Service']))
            $model->attributes = $_GET['Service'];
        $this->render('index', array(
            'model' => $model,
        ));
//        $this->_listService(Service::TYPE_SERVICE);
    }

    /**
     * @return json list of biz and staff are assigned
     */
    public function actionGetAssignService()
    {
        if (isset($_POST['service_id']))
        {
            $sid = $_POST['service_id'];
        }
        else
        {
            $sid = 0;
        }


        $criteria            = new CDbCriteria();
        $criteria->condition = 'sid=:sid';
        $criteria->params    = array(':sid' => $sid);

        if ($this->isBussiness)
        {
            $list_staff = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->getId());
            $criteria->addInCondition('sukey', $list_staff);
        }
        if ($this->isStaff)
        {
            $staff_ukey = Users::getUkeyById(Yii::app()->user->getId());

            $criteria->addCondition('sukey="' . $staff_ukey . '"');
        }

        $service = ServiceStaff::model()->findAll($criteria);


        if ($service == NULL)
        {
            echo json_encode(array());
            Yii::app()->end();
        }
        else
        {
            $arr = array();

            foreach ($service as $s)
            {
                $biz             = Users::getBizbyUkeyStaff($s->sukey);
                $arr['biz_ukey'] = $biz->ukey;
                $arr['biz_name'] = $biz->name;
                $arr['staff'][]  = array(
                    'staff_ukey' => $s->sukey,
                    'staff_name' => Users::getNameByUkey($s->sukey)
                );
            }

            echo json_encode($arr);
            Yii::app()->end();
        }
    }

    public function actionCreate()
    {

        $model       = new Service();
        $model->type = $_GET['t'];
        $staff       = Null;
        $ls_biz      = NULL;
        if ($this->isBussiness)
        {
            //select staff
            $staff = Users::getAllStaffByBusiness(Yii::app()->user->getId(), TRUE);
        }

        if ($this->isAdmin)
        {
            $ls_biz = Users::getAllBussiness(TRUE);
            //author_id
            if (request()->getQuery('at', '') == 'service')
            {
                $bizKey     = user()->getState('bizKey', '');
                $merchantId = Users::getIdByUkey($bizKey);
                if ($merchantId != false)
                {
                    $model->author_id = $merchantId;
                }
            }
        }
        //if isset post
        if (isset($_POST['Service']))
        {
            if (!isset($_POST['sukey']))
            {
                Yii::app()->user->setFlash('error', 'Please assign at least one staff!');
                $this->refresh();
                Yii::app()->end();
            }

            $model->attributes = $_POST['Service'];
            if ($this->isBussiness)
            {
                $model->author_id = Yii::app()->user->id;
            }

            $model->type = isset($_GET['t']) ? $_GET['t'] : 0;
            if ($model->validate() && $model->save())
            {
                if (request()->getQuery('at', '') == 'service')
                {
                    Yii::app()->user->setFlash(
                            'service_form_success', "Create successfully!"
                    );
                }
                else
                {
                    Yii::app()->user->setFlash(
                            'form_success', "Create successfully!"
                    );
                }
                // thêm ảnh mới cho serviceImage
                $firstImage = $this->_uploadServiceImage($model->sid);
                if ($firstImage && !$model->images)
                {
                    $model->images = $firstImage;
                    $model->save();
                }

                if (isset($_POST['delServiceImage']))
                {
                    foreach ($_POST['delServiceImage'] as $sImageId)
                    {
                        $sImage             = ServiceImg::model()->findByPk($sImageId);
                        if ($sImage != null && $sImage->service_id = $model->sid)
                        {
                            @unlink($sImage->image);
                            ServiceImg::model()->deleteByPk($sImageId);
                        }
                    }
                }

                // thêm avatar mới cho service
                $firstAvarta = $this->_uploadPhoto('service', 100, 100, 'fileAvatar');
                if ($firstAvarta && !$model->avatar)
                {
                    $model->avatar = $firstAvarta;
                    $model->save();
                }

                //assign staff
                foreach ($_POST['sukey'] as $skey)
                {

                    $staff_service        = new ServiceStaff();
                    $staff_service->sid   = $model->sid;
                    $staff_service->sukey = $skey;
                    $staff_service->save();
                }
                $this->_ExtraItem($model->sid);
                $type = $_GET['t'] == Service::TYPE_SERVICE ? 'index' : 'room';
                if ($_POST['submit'] == 'continue')
                {
                    if (Yii::app()->request->getQuery('at', '') == 'service')
                    {
                        if (user()->isAdmin())
                        {
//                            $bizKey = user()->getState('bizKey', '');
//                            $this->redirect(array('/bizuser/edit', 'pk' => $bizKey, "#" => "service"));
                            $this->redirect(array('/service/update', 'id' => $model->sid, 'at' => 'service'));
                        }
                    }
                    else
                        $this->redirect(array('/service/update', 'id' => $model->sid));
//                        $this->refresh();
                }
                elseif ($_POST['submit'] == 'merchant')
                {
                    if (Yii::app()->request->getQuery('at', '') == 'service')
                    {
                        if (user()->isAdmin())
                        {
                            $bizKey = user()->getState('bizKey', '');
                            $this->redirect(array('/bizuser/edit', 'pk' => $bizKey, "#" => "service"));
                        }
                    }

                    $this->redirect(Yii::app()->createUrl('service/' . $type, array(
                                'business' => $model->user->ukey)));
                }
                else
                {
                    if (Yii::app()->request->getQuery('at', '') == 'service')
                    {
                        if (user()->isAdmin())
                        {
                            $bizKey = empty(user()->getState('bizKey', '')) ? Users::getUkeyById($model->author_id) : user()->getState('bizKey', '');
                            $this->redirect(array('/bizuser/edit', 'pk' => $bizKey, "#" => "service"));
                        }
                    }
                    $this->redirect(array('service/' . ($_GET['t'] == Service::TYPE_SERVICE ? 'index' : 'room')));
                }
            }
            else
            {
                echo CActiveForm::validate($model);
            }
        }
        $this->render('_form', array(
            'model' => $model,
            'staff' => $staff
        ));
    }

    public function actionGetStaffByUkey()
    {
        $ukey       = $_POST['ukey'];
        $type       = $_POST['type']; //add , edit
        $id_service = $_POST['id']; //

        $this->layout = '//layouts/ajax';
        user()->setState('bizId', $ukey);
        $list_staff   = Users::getStaffByBusinessUkey($ukey);

        echo $this->render('_list_user', array(
            'data' => $list_staff,
            'sid'  => $id_service,
            'type' => $type
        ));
    }

    public function actionGetBizInfo()
    {
        $uid  = $_POST['uid'];
        $arr  = array();
        $ukey = Users::getUkeyById($uid);
        $biz  = Users::getRecordByUkey($ukey);
        if ($biz)
        {
            $arr['address']     = $biz->address;
            $arr['address2']    = $biz->address2;
            $arr['postal_code'] = $biz->postal_code;
//            $arr['ltt'] = $biz->latitude;
//            $arr['lng'] = $biz->longitude;
        }
        echo json_encode($arr);
        Yii::app()->end();
    }

    public function actionGetCategoryBelongBiz()
    {
        if ($_POST['is_new'] == 0)
        {
            $model = new Service();
        }
        else
        {
            $model = Service::model()->findByPk($_POST['is_new']);
        }

        $category = Category::GetAllCategory($_POST['uid']);

        echo $this->renderPartial('_category_list', array(
            'category' => $category,
            'model'    => $model
        ));
        Yii::app()->end();
    }

    public function actionRoom()
    {
        $this->_listService(Service::TYPE_ROOM);
    }

    public function actionAdmin()
    {
        $model             = new Service('search');
        if (isset($_GET['Service']))
            $model->attributes = $_GET['Service'];
        $this->render('index', array(
            'model' => $model,
        ));
    }

    public function _listService($type)
    {
        $this->checkAccess();

        $model       = new Service();
        $model->type = $type;
        $this->_service_form($model, $type);

        $criteria = new CDbCriteria();

        if ($this->isBussiness)
        {
            //select toan bo room thuoc biz quan ly
            $criteria->condition  = 'type=:t AND author_id=:a';
            $criteria->params     = array(
                ':t' => $type,
                ':a' => Yii::app()->user->id
            );
            $this->filterBusiness = Users::getUkeyById(Yii::app()->user->id);
        }
        elseif ($this->isAdmin)
        {
            if (isset($_GET['business']))
            {
                $this->filterBusiness = $_GET['business'];
            }

            if (!$this->filterBusiness)
            {
                $criteria->condition = 'type=:t ';
                $criteria->params    = array(
                    ':t' => $type,
                );
            }
            else
            {
                $criteria->condition = 'type=:t AND author_id=:a';
                $criteria->params    = array(
                    ':t' => $type,
                    ':a' => Users::getIdByUkey($this->filterBusiness)
                );
            }
        }

        if ($this->isAdmin OR $this->isBussiness)
        {
            if (isset($_GET['staff']))
            {
                $this->filterStaff = $_GET['staff'];
            }
            else
            {
                $staffArray = Users::getAllStaffByBusiness($this->filterBusiness, TRUE);
                foreach ($staffArray as $staffId => $staffName)
                {
                    $this->filterStaff = $staffId;
                    break;
                }
            }
        }

        $count           = Service::model()->count($criteria);
        $pages           = new CPagination($count);
        $pages->route    = $this->route;
        $pages->pageSize = $this->currentLimit;
        $pages->applyLimit($criteria);


        $services = Service::model()->findAll($criteria);
        $this->render('service', array(
            'service_model' => $model,
            'services'      => $services,
            'serviceImages' => array(),
            'pages'         => $pages
        ));
    }

    public function actionUpdate()
    {
        $service = Service::model()->findByPk($_GET['id']);
        if ($service == Null)
        {
            throw new CHttpException(404, Yii::t('yii', 'The system is unable to find the Serivce!'));
        }

        if (user()->isMerchant())
        {//is biz or staff
            $list_branch_ids = Merchant::get_id_all_branch(user()->id, TRUE);
            if (!in_array($service->author_id, $list_branch_ids))
            {
                throw new CHttpException(404, Yii::t('yii', 'The system is unable to find the Serivce!'));
            }
        }
        elseif (user()->isBranch())
        {
            if ($service->author_id != user()->id)
                throw new CHttpException(404, Yii::t('yii', 'The system is unable to find the Serivce!'));
        }

        if (isset($_POST['Service']))
        {

            if (!isset($_POST['sukey']))
            {
                Yii::app()->user->setFlash('error', Yii::t('main', 'Please assign at least one staff!'));
                $this->refresh();
                Yii::app()->end();
            }

            $service->attributes = $_POST['Service'];
            if ($service->save())
            {
                //delete all 
                ServiceStaff::model()->deleteAll('sid=:sid', array(
                    ':sid' => $_GET['id'])
                );
                foreach ($_POST['sukey'] as $skey)
                {

                    $staff_service        = new ServiceStaff();
                    $staff_service->sid   = $service->sid;
                    $staff_service->sukey = $skey;
                    $staff_service->save();
                }

                // update ảnh cho serviceImage
                $firstImage = $this->_uploadServiceImage($service->sid);

                if ($firstImage && !$service->images)
                {
                    $service->images = $firstImage;
                    $service->save();
                }

                if (isset($_POST['delServiceImage']))
                {
                    foreach ($_POST['delServiceImage'] as $sImageId)
                    {
                        $sImage             = ServiceImg::model()->findByPk($sImageId);
                        if ($sImage != null && $sImage->service_id = $service->sid)
                        {
                            @unlink($sImage->image);
                            ServiceImg::model()->deleteByPk($sImageId);
                        }
                    }
                }

                // update avatar mới cho service
                $firstAvarta = $this->_uploadPhoto('service', 100, 100, 'fileAvatar');

                if ($firstAvarta && !$service->avatar)
                {
                    $service->avatar = $firstAvarta;
                    $service->update();
                }
                if ($firstAvarta && $service->avatar != null)
                {
                    if ($firstAvarta != $service->avatar)
                    {
                        $service->avatar = $firstAvarta;
                        $service->update();
                    }
                }
                //delete avatar trong service
                if (isset($_POST['delServiceAvarta']))
                {
                    foreach ($_POST['delServiceAvarta'] as $serviceId)
                    {
                        $svAvarta = Service::model()->findByPk($serviceId);
                        if ($svAvarta != null)
                        {
                            @unlink($svAvarta->avatar);
//                            ServiceImg::model()->deleteByPk($sImageId);
                        }
                    }
                }
                if (request()->getQuery('at', '') == 'service')
                {
                    Yii::app()->user->setFlash(
                            'service_form_success', "Update successfully!"
                    );
                }
                else
                {
                    Yii::app()->user->setFlash(
                            'form_success', "Update successfully!"
                    );
                }
                $this->_ExtraItem($service->sid);
                $type = $service->type == Service::TYPE_SERVICE ? 'index' : 'room';
                if ($_POST['submit'] == 'continue')
                {
                    if (Yii::app()->request->getQuery('at', '') == 'service')
                    {
                        if (user()->isAdmin())
                        {
//                            $bizKey = user()->getState('bizKey', '');
//                            $this->redirect(array('/bizuser/edit', 'pk' => $bizKey, "#" => "service"));
                            $this->redirect(array('/service/update', 'id' => $service->sid, 'at' => 'service'));
                        }
                    }
                    else
                        $this->redirect(array('/service/update', 'id' => $service->sid));
//                        $this->refresh();
                }
                elseif ($_POST['submit'] == 'merchant')
                {
                    if (Yii::app()->request->getQuery('at', '') == 'service')
                    {
                        if (user()->isAdmin())
                        {
                            $bizKey = user()->getState('bizKey', '');
                            $this->redirect(array('/bizuser/edit', 'pk' => $bizKey, "#" => "service"));
                        }
                    }
                    $this->redirect(Yii::app()->createUrl('service/' . $type, array(
                                'business' => $service->user->ukey)));
                }
                else
                {
                    if (Yii::app()->request->getQuery('at', '') == 'service')
                    {
                        if (user()->isAdmin())
                        {
                            $bizKey = empty(user()->getState('bizKey', '')) ? Users::getUkeyById($service->author_id) : user()->getState('bizKey', '');
                            $this->redirect(array('/bizuser/edit', 'pk' => $bizKey, "#" => "service"));
                        }
                        else
                        {
                            $this->redirect(array('/bizuser/edit', 'pk' => 'secret_key', "#" => "service"));
                        }
                    }
                    else
                    {
                        $this->redirect(array('service/' . ($service->type == Service::TYPE_SERVICE ? 'index' : 'room')));
                    }
                }
            }
            else
            {
                echo CActiveForm::validate($service);
            }
        }

        $this->render('_form', array(
            'model' => $service
        ));
    }

    public function actionEditService($pk)
    {
        $this->checkAccess();
        $this->_editService($pk, Service::TYPE_SERVICE);
    }

    public function actionEditRoom($pk)
    {
        $this->checkAccess();
        $this->_editService($pk, Service::TYPE_ROOM);
    }

    private function getServiceOrRoom($type)
    {

        $criteria            = new CDbCriteria();
        $criteria->condition = 'status=:status AND type=:type';
        $criteria->params    = array(':type' => $type, ':status' => Service::ACTIVE);

        //list array return
        $array = array();

        if ($this->isStaff)
        {//
            $ukey_staff = Users::getUkeyById(Yii::app()->user->id);
            $sv         = ServiceStaff::model()->findAll('sukey=:sukey', array(
                ':sukey' => $ukey_staff
            ));

            if ($sv == NULL)
            {
                echo json_encode($array);
                Yii::app()->end();
            }
            else
            {

                $ls_service = array();

                foreach ($sv as $k => $v)
                {
                    $ls_service[$k] = $v->sid;
                }

                $criteria->addInCondition('sid', $ls_service);
            }
        }

        if ($this->isBussiness)
        {
            //list all staff
            $list_user = Users::getAllStaffUkeyByBizUkey(Yii::app()->user->id);

            if ($list_user == NULL)
            {
                echo json_encode($array);
                Yii::app()->end();
            }
            else
            {

                //find list service id
                $sri      = new CDbCriteria();
                $sri->addInCondition('sukey', $list_user);
                $sv_staff = ServiceStaff::model()->findAll($sri);

                if ($sv_staff == NUll)
                {
                    echo json_encode($array);
                    Yii::app()->end();
                }
                else
                {
                    $list_sv = array();
                    foreach ($sv_staff as $value)
                    {
                        $list_sv[] = $value->sid;
                    }
                    $criteria->addInCondition('sid', $list_sv);
                }
            }
        }


        $sv = Service::model()->findAll($criteria);

        if ($sv != NULL)
        {
            foreach ($sv as $v)
            {

                if (!$v->category == NULL)
                {

                    $array[] = array(
                        'sid'        => $v->sid,
                        'sname'      => $v->s_name,
                        'sduration'  => $v->duration,
                        'srecover'   => $v->recover,
                        'cat_id'     => $v->category_id,
                        'cat_name'   => $v->category->name,
                        'group_name' => $v->category->group->name
                    );
                }
            }
        }
        return $array;
    }

    public function actionGetServiceByType()
    {

        $arr_service = $this->getServiceOrRoom(Service::TYPE_SERVICE);
        $arr_room    = $this->getServiceOrRoom(Service::TYPE_ROOM);
        $arr_total   = array('service' => $arr_service, 'room' => $arr_room);

        echo json_encode($arr_total);
        Yii::app()->end();
    }

    protected function _editService($pk, $type)
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $this->layout  = '//layouts/ajax';
            $cs            = Yii::app()->clientScript;
            $cs->scriptMap = array(
                'jquery.js'               => false,
                'jquery.yiiactiveform.js' => false,
            );
        }

        $model = Service::model()->findByPk($pk);
        $this->_service_form($model, $type);

        $serviceImages = ServiceImg::model()->findAll("service_id = :sid", array(
            ':sid' => $model->sid
        ));

        $this->render('_service_form', array(
            'model'         => $model,
            'serviceImages' => $serviceImages,
        ));
    }

    protected function _service_form($model, $type)
    {
        $form_id = $type == Service::TYPE_ROOM ? 'room' : 'service';
        $form_id .= '-form' . $model->isNewRecord ? '-add' : '-edit';

        if (Yii::app()->request->isAjaxRequest && @$_POST['ajax'] == $form_id)
        {
            $model->attributes = $_POST['Service'];
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST['Service']))
        {
            if ($this->isBussiness)
            {
                $model->author_id = Yii::app()->user->id;
            }

            $model->type       = $type;
            $model->attributes = $_POST['Service'];
            if (!$model->validate())
            {
                Yii::app()->user->setFlash('form_error', 'Please fill correct information!');
            }
            else
            {
                $action = $model->isNewRecord ? 'Add' : 'Edit';
                if ($model->save())
                {
                    /**
                     * Upload ảnh mới và xóa ảnh cũ
                     */
                    $firstImage = $this->_uploadServiceImage($model->sid);
                    if ($firstImage && !$model->images)
                    {
                        $model->images = $firstImage;
                        $model->save();
                    }

                    Yii::app()->user->setFlash('form_success', "$action is successfully!");

                    if (isset($_POST['delServiceImage']))
                    {
                        foreach ($_POST['delServiceImage'] as $sImageId)
                        {
                            $sImage             = ServiceImg::model()->findByPk($sImageId);
                            if ($sImage != null && $sImage->service_id = $model->sid)
                            {
                                @unlink($sImage->image);
                                ServiceImg::model()->deleteByPk($sImageId);
                            }
                        }
                    }

                    $this->redirect($type == Service::TYPE_SERVICE ? 'index' : 'room');
                }
                else
                {
                    Yii::app()->user->setFlash('form_error', 'Error, please try again!');
                }
            }
        }
    }

    protected function _uploadServiceImage($service_id)
    {
        $dir = 'service';

        if (@$_FILES['file'])
        {
            $iArray = array();
            foreach ($_FILES['file']['name'] as $fkey => $fname)
            {
                // Lấy extension của file và tạo tên file mới
                $ext      = pathinfo($fname, PATHINFO_EXTENSION);
                $tmp_file = "files/$dir/" . md5(time() . $fname) . ".$ext";

                // Move file vào thư mục cần lưu                
                if (@move_uploaded_file($_FILES['file']['tmp_name'][$fkey], $tmp_file))
                {
                    // Resize ảnh
                    $thumb = Yii::app()->phpThumb->create($tmp_file);
                    $thumb->save($tmp_file);

                    // Lưu vào csdl
                    $si             = new ServiceImg();
                    $si->service_id = $service_id;
                    $si->image      = $tmp_file;
                    $si->save();

                    $iArray[] = $si->id;
                }
            }
        }

        if (!empty($iArray))
        {
            return current($iArray);
        }
        else
        {
            return FALSE;
        }
    }

    public function actionDeleteService($pk)
    {
        if (!$this->checkAccess('', '', TRUE))
        {
            echo json_encode(array(
                'err' => 1,
                'msg' => 'Access deny!'
            ));
            return;
        }
        else
        {
            $this->_deleteService($pk, Service::TYPE_SERVICE);
        }
    }

    public function actionDeleteRoom($pk)
    {
        if (!$this->checkAccess('', '', TRUE))
        {
            echo json_encode(array(
                'err' => 1,
                'msg' => 'Access deny!'
            ));
            return;
        }
        else
        {
            $this->_deleteService($pk, Service::TYPE_ROOM);
        }
    }

    public function _deleteService($pk, $type)
    {
        $delStatus = Service::model()->deleteByPk($pk, "type=:t", array(
            ':t' => $type
        ));

        if ($delStatus)
        {
            ServiceStaff::model()->deleteAll('sid=:sid', array(
                ':sid' => $pk
            ));
            echo json_encode(array(
                'err' => 0,
                'msg' => 'Delete Successful!'
            ));
            return;
        }
        else
        {
            echo json_encode(array(
                'err' => 1,
                'msg' => 'Error, please try again!'
            ));
            return;
        }
    }

    function actionGenExtraRow()
    {
        echo $this->renderPartial('extra/item');
    }

    function _ExtraItem($sid)
    {
        if (isset($_POST['ExtraService']))
        {
            foreach ($_POST['ExtraService'] as $id => $v)
            {
                if ($v['name'] != '' && $v['duration'] != '')
                {
                    $model_extra = ExtraService::model()->findByPk($id);
                    if ($model_extra == NULL)
                    {
                        $model_extra      = new ExtraService;
                        $model_extra->sid = $sid;
                    }
                    $model_extra->name       = $v['name'];
                    $model_extra->duration   = $v['duration'];
                    $model_extra->from_price = $v['from_price'];
                    $model_extra->to_price   = $v['to_price'];
                    $model_extra->save();
                }
            }
        }
    }

    function actionDeleteExtraitem()
    {
        if ($this->isAdmin)
        {
            try
            {
                ExtraService::model()->deleteByPk($_GET['id']);
            }
            catch (Exception $exc)
            {
                
            }
        }
        elseif ($this->isBussiness)
        {
            $record = ExtraService::model()->findByPk($_GET['id']);
            if ($record->service->author_id == Yii::app()->user->id)
                $record->delete();
        }
        Yii::app()->user->setFlash('success', 'Deleted Item!');
        $this->redirect(Yii::app()->request->urlReferrer);
    }

    public function actionUpdateServiceAlias()
    {
        $models = Service::model()->findAll();
        foreach ($models as $model)
        {
            $model->alias = Utility::createAlias($model, $model->s_name);
            $model->update(array('alias'));
        }
    }

}

/** 
 * End file ServiceController
 */
